package com.qf.rabbitmq1.route;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerMain {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        //服务器所在机器的ip（如果是安装在虚拟机，写虚拟机ip）
        factory.setHost("localhost");
        //amqp协议端口
        factory.setPort(5672);
        //虚拟主机名
        factory.setVirtualHost("cdm");
        //设置虚拟主机对应用户名和密码
        factory.setUsername("cdm");
        factory.setPassword("cdm");

        //获取连接对象（Connection）
        Connection conn = factory.newConnection();
        //获取channel
        Channel channel = conn.createChannel();

        //声明交换机
        /*
            exchange – 交换机名称
            type – 交换机类型（FANOUT--发布订阅模式\DIRECT--路由模式\TOPIC--话题模式）
            durable – 是否支持持久化
            autoDelete – 是否自动删除
            internal – 是否是内部交换机
            arguments – 额外参数
         */
        channel.exchangeDeclare("route.ex", BuiltinExchangeType.DIRECT,true,false,false,null);

        //声明队列
        channel.queueDeclare("route.queue1",true,false,false,null);
        channel.queueDeclare("route.queue2",true,false,false,null);

        //绑定队列和交换机
        //交换机的类型为DIRECT,进行消息路由时，根据消息的路由键，将消息转发到对应的队列上（路由键必须是精确的，不支持通配符）
        channel.queueBind("route.queue1","route.ex","A");
        channel.queueBind("route.queue2","route.ex","B");

        //发送消息
        channel.basicPublish("route.ex","A",null,("hello route exA1").getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("route.ex","A",null,("hello route exA2").getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("route.ex","B",null,("hello route exB1").getBytes(StandardCharsets.UTF_8));

        channel.close();
        conn.close();
    }
}
